<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="React,">










<meta name="description" content="React###1. 当组件的props或state发生变化时，就会重新执行render 函数 ###2. 当父组件的render函数被运行时，子组件的render也会被执行一次 3.生命周期函数（组件） componentWillMount()：在组件即将被挂载到页面上的时刻自动执行（只在第一次被挂载的时候执行，只执行一次）  render()：在组件被挂载的时候自动执行（必须存在的生命周期函数">
<meta name="keywords" content="React">
<meta property="og:type" content="article">
<meta property="og:title" content="react入门">
<meta property="og:url" content="http://zhanglei_c.gitee.io/blog/2020/01/16/react入门/index.html">
<meta property="og:site_name" content="爱吃零食的猫">
<meta property="og:description" content="React###1. 当组件的props或state发生变化时，就会重新执行render 函数 ###2. 当父组件的render函数被运行时，子组件的render也会被执行一次 3.生命周期函数（组件） componentWillMount()：在组件即将被挂载到页面上的时刻自动执行（只在第一次被挂载的时候执行，只执行一次）  render()：在组件被挂载的时候自动执行（必须存在的生命周期函数">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-16T14:09:56.081Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="react入门">
<meta name="twitter:description" content="React###1. 当组件的props或state发生变化时，就会重新执行render 函数 ###2. 当父组件的render函数被运行时，子组件的render也会被执行一次 3.生命周期函数（组件） componentWillMount()：在组件即将被挂载到页面上的时刻自动执行（只在第一次被挂载的时候执行，只执行一次）  render()：在组件被挂载的时候自动执行（必须存在的生命周期函数">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://zhanglei_c.gitee.io/blog/2020/01/16/react入门/">





  <title>react入门 | 爱吃零食的猫</title>
  








</head>

<script type="text/javascript" color="0,0,255" opacity="0.7" zindex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
<a href="https://github.com/403NotFound" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">爱吃零食的猫</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">自由，平等，公正，法治</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zhanglei_c.gitee.io/blog/blog/2020/01/16/react入门/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Zhang_lei">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="爱吃零食的猫">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">react入门</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-01-16T22:09:30+08:00">
                2020-01-16
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="React"><a href="#React" class="headerlink" title="React"></a>React</h2><p>###1. 当组件的props或state发生变化时，就会重新执行render 函数</p>
<p>###2. 当父组件的render函数被运行时，子组件的render也会被执行一次</p>
<h3 id="3-生命周期函数（组件）"><a href="#3-生命周期函数（组件）" class="headerlink" title="3.生命周期函数（组件）"></a>3.生命周期函数（组件）</h3><ul>
<li><p><code>componentWillMount()</code>：在组件即将被挂载到页面上的时刻自动执行（<strong>只在第一次被挂载的时候执行，只执行一次</strong>）</p>
</li>
<li><p><code>render()</code>：在组件被挂载的时候自动执行（<strong>必须存在的生命周期函数</strong>）</p>
</li>
<li><p><code>componentDidMount()</code>：在组件被挂载到页面之后自动执行（<strong>只在被挂载完成之后执行，只执行一次</strong>）</p>
</li>
<li><p><code>shouldComponentUpdate()</code>：组件被更新之前，会自动执行（<strong>返回一个布尔值</strong>）</p>
</li>
<li><p><code>componentWillUpdate()</code>：</p>
<ul>
<li><blockquote>
<ol>
<li>组件被更新之前会自动执行，但是他在shouldComponentUpdate之后执行</li>
<li>如果shouldComponentUpdate返回true他才会执行</li>
<li>如果返回false,则不会执行</li>
</ol>
</blockquote>
</li>
</ul>
</li>
<li><p><code>componentDidUpdate()</code>：组件更新完成之后会被执行</p>
</li>
<li><p><code>componentReceiveProps()</code>：</p>
<ul>
<li><blockquote>
<ol>
<li>一个组件需要从父组件接收参数</li>
<li>只要父组件的render函数被重新执行了，子组件的生命周期函数就会被执行</li>
<li>组件第一次存在于父组件中，不会执行</li>
<li>如果这个组件之前已经存在于父组件中，才会执行</li>
</ol>
</blockquote>
</li>
</ul>
</li>
<li><p><code>componentWillUnmount()</code>：当组件即将从页面中销毁的时候，才会被执行</p>
</li>
</ul>
<h3 id="4-Ajax一般放在componentDidMound这个钩子函数中去请求"><a href="#4-Ajax一般放在componentDidMound这个钩子函数中去请求" class="headerlink" title="4. Ajax一般放在componentDidMound这个钩子函数中去请求"></a>4. Ajax一般放在<code>componentDidMound</code>这个钩子函数中去请求</h3><h3 id="5-Fragment占位符不会渲染成任何标签元素"><a href="#5-Fragment占位符不会渲染成任何标签元素" class="headerlink" title="5.Fragment占位符不会渲染成任何标签元素"></a>5.<code>Fragment</code>占位符不会渲染成任何标签元素</h3><h2 id="Redux"><a href="#Redux" class="headerlink" title="Redux"></a>Redux</h2><h3 id="1-ActionTypes封装"><a href="#1-ActionTypes封装" class="headerlink" title="1.ActionTypes封装"></a>1.ActionTypes封装</h3><ul>
<li>有利于程序的维护以及出现bug时快速定位</li>
<li>字符串类型的拼写错误浏览器不会报错，以至于不容易定位错误</li>
</ul>
<h3 id="2-无状态组件"><a href="#2-无状态组件" class="headerlink" title="2.无状态组件"></a>2.无状态组件</h3><ul>
<li>当一个组件只有一个<code>render</code>函数时，我们可以定义这个组件为一个无状态组件</li>
<li>无状态组件定义一个组件为一个函数</li>
<li>无状态组件的性能要比普通组件更优（因为没有普通组件那么多生命周期函数）</li>
</ul>
<h3 id="3-解决-create-react-app-安装依赖速度太慢"><a href="#3-解决-create-react-app-安装依赖速度太慢" class="headerlink" title="3.解决 create-react-app 安装依赖速度太慢"></a>3.解决 <code>create-react-app</code> 安装依赖速度太慢</h3><figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">npm config set registry https://registry.npm.taobao.org</span><br><span class="line"><span class="comment"># 配置后可通过下面方式来验证是否成功</span></span><br><span class="line">npm config get registry</span><br><span class="line"><span class="comment"># 显示出上述地址的话就是更换成功</span></span><br></pre></td></tr></table></figure>
<p>然后再去使用 <code>create-react-app</code>去构建项目就ok啦</p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">create-react-app projectName</span><br></pre></td></tr></table></figure>
<h3 id="4-styled-components-中-injectGlobal-被废弃"><a href="#4-styled-components-中-injectGlobal-被废弃" class="headerlink" title="4.styled-components 中 injectGlobal 被废弃"></a>4.<code>styled-components</code> 中 <code>injectGlobal</code> 被废弃</h3><blockquote>
<p>injectGlobal 被 createGlobalStyle 代替</p>
</blockquote>
<p>style.js</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; createGlobalStyle &#125; <span class="keyword">from</span> <span class="string">'styled-components'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> GlobalStyle = createGlobalStyle<span class="string">`</span></span><br><span class="line"><span class="string">  body &#123;</span></span><br><span class="line"><span class="string">    margin: 0px;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">`</span></span><br></pre></td></tr></table></figure>
<p>App.js</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">import React, &#123; Component, Fragment &#125; from &apos;react&apos;;</span><br><span class="line">import &#123; GlobalStyle &#125; from &apos;./style.js&apos;;</span><br><span class="line"></span><br><span class="line">class App extends Component &#123;</span><br><span class="line">  constructor(props) &#123;</span><br><span class="line">    super(props)</span><br><span class="line">  &#125;</span><br><span class="line">  render() &#123;</span><br><span class="line">    return (</span><br><span class="line">      &lt;Fragment&gt;</span><br><span class="line">        &lt;GlobalStyle /&gt;</span><br><span class="line">        &lt;div&gt;</span><br><span class="line">          hello world</span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">      &lt;/Fragment&gt;</span><br><span class="line">    )</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">export default App;</span><br></pre></td></tr></table></figure>
<h3 id="5-react-transition-group插件的使用注意事项"><a href="#5-react-transition-group插件的使用注意事项" class="headerlink" title="5.react-transition-group插件的使用注意事项"></a>5.<code>react-transition-group</code>插件的使用注意事项</h3><ol>
<li><p>安装</p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i react-transition-group -S</span><br></pre></td></tr></table></figure>
</li>
<li><p>导入并使用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">import &#123; CSSTransition &#125; from &apos;react-transition-group&apos;</span><br><span class="line"></span><br><span class="line">&lt;CSSTransition</span><br><span class="line">in=&#123;this.state.focused&#125; // 动画触发的条件</span><br><span class="line">timeout=&#123;200&#125; // 动画执行的时间</span><br><span class="line">classNames=&quot;slide&quot; // 指定的类名注意是 classNames 而不是 className</span><br><span class="line">&gt;</span><br><span class="line">    &lt;NavSearch </span><br><span class="line">       className=&#123;this.state.focused ? &apos;focused&apos; : &apos;&apos;&#125;</span><br><span class="line">       onFocus=&#123;this.handleInputFocus&#125;</span><br><span class="line">       onBlur=&#123;this.handleInputBlur&#125;</span><br><span class="line">     /&gt;</span><br><span class="line">&lt;/CSSTransition&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>样式编写</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">// 上述指定的 classNames 来进行样式的编写</span><br><span class="line"><span class="selector-class">.slide-enter</span> &#123;</span><br><span class="line">    <span class="attribute">transition</span>: all .<span class="number">2s</span> ease-out;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-class">.slide-enter-active</span> &#123;</span><br><span class="line">    <span class="attribute">width</span>: <span class="number">320px</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-class">.slide-exit</span> &#123;</span><br><span class="line">    <span class="attribute">transition</span>: all .<span class="number">2s</span> ease-out;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-class">.slide-exit-active</span> &#123;</span><br><span class="line">    <span class="attribute">width</span>: <span class="number">240px</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="6-redux和react-redux的使用"><a href="#6-redux和react-redux的使用" class="headerlink" title="6.redux和react-redux的使用"></a>6.<code>redux</code>和<code>react-redux</code>的使用</h3><ol>
<li><p>安装 <code>redux</code> 和 <code>react-redux</code></p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm i redux -S</span><br><span class="line">npm i react-redux -S</span><br></pre></td></tr></table></figure>
</li>
<li><p>创建 <code>store</code></p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">cd src</span><br><span class="line">mkdir store</span><br><span class="line">cd store</span><br><span class="line">touch index.js</span><br><span class="line">touch reducer.js</span><br></pre></td></tr></table></figure>
<p><strong>index.js</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; createStore &#125; <span class="keyword">from</span> <span class="string">'redux'</span></span><br><span class="line"><span class="keyword">import</span> reducer <span class="keyword">from</span> <span class="string">'./reducer'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> store = createStore(reducer)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> store;</span><br></pre></td></tr></table></figure>
<p><strong>reducer.js</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 定义默认数据</span></span><br><span class="line"><span class="keyword">const</span> defaultState = &#123;</span><br><span class="line">  focused: <span class="literal">false</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> (state = defaultState, action) =&gt; &#123;</span><br><span class="line">  <span class="comment">// 根据action的type类型做出相应的逻辑</span></span><br><span class="line">  <span class="keyword">if</span> (action.type === <span class="string">'search_focus'</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      focused: <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (action.type === <span class="string">'search_blur'</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      focused: <span class="literal">false</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> state;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>App.js</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; Component, Fragment &#125; <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; GlobalStyle &#125; <span class="keyword">from</span> <span class="string">'./style.js'</span>;</span><br><span class="line"><span class="comment">// 引入 store</span></span><br><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">'./store/index'</span></span><br><span class="line"><span class="keyword">import</span> &#123; GlobalIconFont &#125; <span class="keyword">from</span> <span class="string">'./static/iconfont/iconfont.js'</span>;</span><br><span class="line"><span class="keyword">import</span> Header <span class="keyword">from</span> <span class="string">'./common/header/index'</span></span><br><span class="line"><span class="comment">// 使用 provider 将 store 中的数据传入子组件</span></span><br><span class="line"><span class="keyword">import</span> &#123; Provider &#125; <span class="keyword">from</span> <span class="string">'react-redux'</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">App</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;Fragment&gt;</span><br><span class="line">        &lt;GlobalStyle /&gt;</span><br><span class="line">        &lt;GlobalIconFont /&gt;</span><br><span class="line">        &lt;Provider store=&#123;store&#125;&gt;</span><br><span class="line">          &lt;Header /&gt;</span><br><span class="line">        &lt;<span class="regexp">/Provider&gt;</span></span><br><span class="line"><span class="regexp">      &lt;/</span>Fragment&gt;</span><br><span class="line">    )</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> App;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol start="3">
<li><p>组件中引入<code>store</code>和<code>connect</code></p>
<p><strong>common/header/index</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">import &#123; connect &#125; from &apos;react-redux&apos;</span><br><span class="line">class Header extends Component &#123;</span><br><span class="line">    //...逻辑</span><br><span class="line">    this.props.focused</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">const mapStateToProps = (state) =&gt; &#123;</span><br><span class="line">  return &#123;</span><br><span class="line">    // 从 store 取数据 focused 赋值给 focused,</span><br><span class="line">    focused: state.focused</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">const mapDispatchToProps = (dispatch) =&gt; &#123;</span><br><span class="line">  // 派发 dispatch</span><br><span class="line">  return &#123;</span><br><span class="line">    handleInputFocus() &#123;</span><br><span class="line">      const action = &#123;</span><br><span class="line">        type: &apos;search_focus&apos;</span><br><span class="line">      &#125;;</span><br><span class="line">      dispatch(action)</span><br><span class="line">    &#125;,</span><br><span class="line">    handleInputBlur() &#123;</span><br><span class="line">      const action = &#123;</span><br><span class="line">        type: &apos;search_blur&apos;</span><br><span class="line">      &#125;;</span><br><span class="line">      dispatch(action)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">export default connect(mapStateToProps, mapDispatchToProps)(Header);</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="7-优化reducer"><a href="#7-优化reducer" class="headerlink" title="7.优化reducer"></a>7.优化<code>reducer</code></h3><blockquote>
<p>如果所有的 reducer 均写在 store 下的 reducer.js中，那么reducer中的代码将会越来越大，所以我们需要将reducer分组再导入会优化一些代码结构，方便维护。</p>
</blockquote>
<p><strong>common/header/store</strong>(在header下创建store,store中创建redudcer.js和index.js)</p>
<p><strong>common/header/store/reducer.js</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 定义默认数据</span></span><br><span class="line"><span class="keyword">const</span> defaultState = &#123;</span><br><span class="line">  focused: <span class="literal">false</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> (state = defaultState, action) =&gt; &#123;</span><br><span class="line">  <span class="comment">// 根据action的type类型做出相应的逻辑</span></span><br><span class="line">  <span class="keyword">if</span> (action.type === <span class="string">'search_focus'</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      focused: <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (action.type === <span class="string">'search_blur'</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      focused: <span class="literal">false</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> state;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>common/header/store/index.js</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方便外部文件引入header中的reducer</span></span><br><span class="line"><span class="keyword">import</span> reducer <span class="keyword">from</span> <span class="string">'./reducer'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> &#123; reducer &#125;</span><br></pre></td></tr></table></figure>
<p><strong>src/store/reducer.js</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; reducer <span class="keyword">as</span> headerReducer &#125; <span class="keyword">from</span> <span class="string">'../common/header/store/index'</span></span><br><span class="line"><span class="comment">// 使用 combineReducers 来结合各组件之间的 reducer</span></span><br><span class="line"><span class="keyword">import</span> &#123; combineReducers &#125; <span class="keyword">from</span> <span class="string">'redux'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> reducer = combineReducers(&#123;</span><br><span class="line">  header: headerReducer</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> reducer;</span><br></pre></td></tr></table></figure>
<p><strong><code>Notice</code></strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">// src/common/header/index.js</span><br><span class="line">const mapStateToProps = (state) =&gt; &#123;</span><br><span class="line">  return &#123;</span><br><span class="line">    // 从 store 取数据 focused 赋值给 focused,此时拿store中的数据要从上面定义的header中拿</span><br><span class="line">    focused: state.header.focused</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/React/" rel="tag"># React</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/12/17/剑指Offer-7/" rel="next" title="剑指Offer(7)">
                <i class="fa fa-chevron-left"></i> 剑指Offer(7)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2020/03/26/centos下安装MongoDB/" rel="prev" title="centos下安装MongoDB">
                centos下安装MongoDB <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Zhang_lei</p>
              <p class="site-description motion-element" itemprop="description">爱吃零食的猫</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/403NotFound" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/ai-chi-bao-mi-hua-de-mao/activities" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-send"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/ZhangLei_c" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-github-alt"></i>码云</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5205419998/profile?rightmod=1&wvr=6&mod=personinfo&is_all=1" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#React"><span class="nav-number">1.</span> <span class="nav-text">React</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-生命周期函数（组件）"><span class="nav-number">1.1.</span> <span class="nav-text">3.生命周期函数（组件）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-Ajax一般放在componentDidMound这个钩子函数中去请求"><span class="nav-number">1.2.</span> <span class="nav-text">4. Ajax一般放在componentDidMound这个钩子函数中去请求</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-Fragment占位符不会渲染成任何标签元素"><span class="nav-number">1.3.</span> <span class="nav-text">5.Fragment占位符不会渲染成任何标签元素</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redux"><span class="nav-number">2.</span> <span class="nav-text">Redux</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-ActionTypes封装"><span class="nav-number">2.1.</span> <span class="nav-text">1.ActionTypes封装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-无状态组件"><span class="nav-number">2.2.</span> <span class="nav-text">2.无状态组件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-解决-create-react-app-安装依赖速度太慢"><span class="nav-number">2.3.</span> <span class="nav-text">3.解决 create-react-app 安装依赖速度太慢</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-styled-components-中-injectGlobal-被废弃"><span class="nav-number">2.4.</span> <span class="nav-text">4.styled-components 中 injectGlobal 被废弃</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-react-transition-group插件的使用注意事项"><span class="nav-number">2.5.</span> <span class="nav-text">5.react-transition-group插件的使用注意事项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-redux和react-redux的使用"><span class="nav-number">2.6.</span> <span class="nav-text">6.redux和react-redux的使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-优化reducer"><span class="nav-number">2.7.</span> <span class="nav-text">7.优化reducer</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zhang_lei</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>


<div>
<span id="busuanzi_container_site_pv">
  本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span id="busuanzi_container_site_uv">
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
